const Controller = require('../core/base_controller');
const fs = require('mz/fs');
const path = require('path');
class UploadController extends Controller {
  async upload(ctx) {
    const file = ctx.request.files[0];
    const fileInfo = fs.readFileSync(file.filepath);
    console.log('上传文件为' + file.filename);
    const name = path.basename(file.filename);
    const target = path.join(this.config.baseDir, `app/public/upload/${name}`);
    /**
     * 本地存储路径
     * const target = path.join(this.config.baseDir, `app/public/upload/${name}`);
     *
     * 官方oss路径
     * const name = "egg-multipart-test/" + path.basename(file.filename);
     *
     * 网友
     * const name = "egg-oss-demo/" + ctx.genID(10) + path.extname(file.filename);
     */
    let result;
    try {
      fs.writeFileSync(target, fileInfo);
      // 上传oss并返回结果
      //   result = await ctx.oss.put(name, file.filepath);
    } catch (error) {
      throw error;
    } finally {
      // 需要删除临时文件
      await fs.unlink(file.filepath);
    }
    console.log(result);
    if (!result) {
      this.notFound('上传失败');
    }
    this.success({
      url: result.url,
      // 获取所有的字段值
      requestBody: ctx.request.body,
    });
  }

  //   上传多个文件
  async uploadMulti(ctx) {
    for (const file of ctx.request.files) {
      console.log('field: ' + file.fieldname);
      文件名;
      console.log('filename: ' + file.filename); // 文件名
      console.log('encoding: ' + file.encoding); // 文件的编码格式
      console.log('mime: ' + file.mime);
      console.log('tmp filepath: ' + file.filepath); // 文件路径
      let result;
      try {
        const name = 'egg-multipart-test/' + path.basename(file.filename);
        result = await ctx.oss.put(name, file.filepath);
      } finally {
        await fs.unlink(file.filepath);
      }
      if (!result) {
        this.fail('上传失败');
      }
      this.success({
        url: result.url,
        requestBody: ctx.request.body,
      });
    }

    // 官方
    const name = 'egg-multipart-test/' + path.basename(file.filename);
    // 网友
    // const name = "egg-oss-demo/" + ctx.genID(10) + path.extname(file.filename);
    let result;
    try {
      // 处理文件
      result = await ctx.oss.put(name, file.filepath);
    } finally {
      // 需要删除临时文件
      await fs.unlink(file.filepath);
    }
    if (!result) {
      this.fail('上传失败');
    }
    this.success({
      url: result.url,
      requestBody: ctx.request.body,
    });
  }
}

module.exports = UploadController;
